package cn.com.hhrcw.service.impl;

import cn.com.hhrcw.constant.CommonConstant;
import cn.com.hhrcw.forest.HuaWeiRoomAPI;
import cn.com.hhrcw.service.HuaWeiRoomService;
import cn.com.hhrcw.utils.huawei.CreateMeetingParam;
import cn.com.hhrcw.utils.huawei.HmacSHA256;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.utils.UuidUtils;
import org.jeecg.common.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;

import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @ProjectName: recruit-boot-parent
 * @Package: cn.com.hhrcw.service.impl
 * @ClassName: HuaWeiRoomServiceImpl
 * @Author: 朱修轩
 * @Description:
 * @Date: 2021/5/18 15:38
 * @Version: 1.0
 */
@Slf4j
@Service
public class HuaWeiRoomServiceImpl implements HuaWeiRoomService {

    //userName=18638610097

    private static final String USER_NAME_ZXX = "18738596041";

    private static final String PASS_WORD_ZXX = "123456789!";

    // passWord=huirong@123A

    private static final String APP_ID = "bfeda7c55b6f4ece834a9353e13fa651";

    private static final String APP_KEY = "e93d6141159b8b75013b44762bf5b1a0926b33390e7827c4e61a7423eb1363bf";

    @Autowired
    private HuaWeiRoomAPI huaWeiRoomApi;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public String getToken2() {
        boolean flag = redisUtil.hasKey("HuaWeiYunToken");
        if (flag) {
            return redisUtil.get("HuaWeiYunToken").toString();
        }
        String userId = "";
        Map<String, Object> headersMap = new HashMap<>(5);
        long expireTime = System.currentTimeMillis() / 1000 + 60 * 10;
        String nonce = UuidUtils.getUUID().substring(0, 32);
        String authorization = HmacSHA256.encode(APP_ID + ":" + userId + ":" + expireTime + ":" + nonce, APP_KEY);
        headersMap.put("Authorization", "HMAC-SHA256 signature=" + authorization);
        headersMap.put(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE);

        Map<String, Object> body = new HashMap<>(5);
        body.put("appId", APP_ID);
        body.put("clientType", 0);
        body.put("expireTime", expireTime);
        body.put("nonce", nonce);
        body.put("userId", userId);
        try {
            JSONObject json = huaWeiRoomApi.appAuth(headersMap, body);
            String accessToken = json.getString("accessToken");
            redisUtil.set("HuaWeiYunToken", accessToken, 60);
            return accessToken;
        } catch (Exception e) {
            log.info("鉴权失败");
            log.error(e.getMessage(), e);
        }
        return null;
    }

    @Override
    public String getToken() {
        boolean flag = redisUtil.hasKey("HuaWeiYunToken");
        if (flag) {
            return redisUtil.get("HuaWeiYunToken").toString();
        }
        Map<String, Object> headersMap = new HashMap<>(5);
        String authorization = Base64.getEncoder().encodeToString((USER_NAME_ZXX + ":" + PASS_WORD_ZXX).getBytes());
        headersMap.put("Authorization", "basic " + authorization);
        headersMap.put(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE);
        Map<String, Object> body = new HashMap<>(5);
        body.put("account", USER_NAME_ZXX);
        body.put("clientType", 72);
        body.put("createTokenType", 0);
        try {
            JSONObject json = huaWeiRoomApi.authLogin(headersMap, body);
            log.info("鉴权华为云会议室结果: {}", json);
            long expireTime = json.getLongValue("expireTime");
            String accessToken = json.getString("accessToken");
            long time = System.currentTimeMillis() / 1000;
            long l = expireTime - time;
            redisUtil.set("HuaWeiYunToken", accessToken, l);
            return accessToken;
        } catch (Exception e) {
            log.info("鉴权失败");
            log.error(e.getMessage(), e);
        }
        return null;
    }

    @Override
    public JSONObject createMeeting(CreateMeetingParam param) {
        Map<String, Object> headersMap = new HashMap<>(5);
        String token = this.getToken();
        log.info("token::::" + token);
        if (null == token) {
            return new JSONObject();
        }
        headersMap.put(CommonConstant.TOKEN, token);
        headersMap.put(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE);
        try {
            JSONArray jsonArray = huaWeiRoomApi.conferences(headersMap, param);
            log.info("创建华为云会议结果:" + jsonArray.toJSONString());
            return jsonArray.getJSONObject(0);
        } catch (Exception e) {
            log.error("创建华为云会议" + e.getMessage(), e);
        }
        return new JSONObject();
    }

    @Override
    public JSONArray meetingList() {
        Map<String, Object> headersMap = new HashMap<>(5);
        String token = this.getToken();
        if (null == token) {
            return new JSONArray();
        }
        headersMap.put(CommonConstant.TOKEN, token);
        try {
            Map<String, Object> body = new HashMap<>(5);
            body.put("limit", 100);
            body.put("specialVmr", null);
            JSONObject jsonObject = huaWeiRoomApi.getList(headersMap, body);
            log.info("获取会议室列表结果" + jsonObject.toJSONString());
            JSONArray data = jsonObject.getJSONArray("data");
            log.info("--------------------------获取到会议室总数" + data.size());
            return data;
        } catch (Exception e) {
            log.error("获取华为会议室列表错误：" + e.getMessage(), e);
        }
        return new JSONArray();
    }

    @Override
    public JSONArray meetingList2(String searchKey) {
        Map<String, Object> headersMap = new HashMap<>(5);
        String token = this.getToken();
        if (null == token) {
            return new JSONArray();
        }
        headersMap.put(CommonConstant.TOKEN, token);
        try {
            Map<String, Object> body = new HashMap<>(5);
            body.put("limit", 100);
            body.put("specialVmr", null);
            body.put("searchKey", searchKey);
            JSONObject jsonObject = huaWeiRoomApi.getList(headersMap, body);
            log.info("获取会议室列表结果" + jsonObject.toJSONString());
            JSONArray data = jsonObject.getJSONArray("data");
            log.info("--------------------------获取到会议室总数" + data.size());
            return data;
        } catch (Exception e) {
            log.error("获取华为会议室列表错误：" + e.getMessage(), e);
        }
        return new JSONArray();
    }

    @Override
    public Boolean cancelMeeting(String conferenceId) {
        String token = this.getToken();
        if (null == token) {
            return false;
        }
        Map<String, Object> headersMap = new HashMap<>(5);
        log.info("token:::" + token);
        log.info("conferenceID:::" + conferenceId);
        headersMap.put(CommonConstant.TOKEN, token);
        Map<String, Object> body = new HashMap<>(5);
        body.put("conferenceID", conferenceId);
        body.put("type", 1);
        try {
            huaWeiRoomApi.cancel(headersMap, body);
            log.info("取消会议成功");
            return true;
        } catch (Exception e) {
            log.error("取消会议异常" + e.getMessage(), e);
            return false;
        }
    }

    @Override
    public Boolean updateMeeting(String conferenceId, CreateMeetingParam param) {
        Map<String, Object> headersMap = new HashMap<>(5);
        String token = this.getToken2();
        if (null == token) {
            return false;
        }
        headersMap.put(CommonConstant.TOKEN, token);
        headersMap.put(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE);
        try {
            huaWeiRoomApi.update(conferenceId, headersMap, param);
            return true;
        } catch (Exception e) {
            log.error("修改会议室信息错误" + e.getMessage(), e);
        }
        return false;
    }
}
